package com.crm.shiro;

import com.crm.entity.Permission;
import com.crm.entity.Role;
import com.crm.entity.User;
import com.crm.repository.PermissionRepository;
import com.crm.service.impl.UserServiceImpl;
import com.crm.util.MD5;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class CustomRealm extends  AuthorizingRealm{

	@Autowired
	private UserServiceImpl userService;
	@Autowired
	private PermissionRepository permissionRepository;
	
	/**
	 * 授权
	 */
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection arg0) {
		System.out.println("授权");
		//让shiro知道主体拥有哪些权限
		//通过arg0获取操作主体
		User user = (User) arg0.getPrimaryPrincipal();
		//让主体知道有那么些权限
		SimpleAuthorizationInfo simpleAuthorizationInfo=new SimpleAuthorizationInfo();
		List<Permission> perMission = permissionRepository.getPerMission(user.getUserId());
		System.out.println("赵祺permision"+perMission);
		Set<String> permissons=new HashSet<String>();
		for( Role role:user.getRlist()) {
			//给角色
			simpleAuthorizationInfo.addRole(role.getRoleName());

			for(Permission p:perMission) {
				permissons.add(p.getPermissionValue());
				System.out.println("permision"+p.getPermissionValue());
				//给权限
			//	simpleAuthorizationInfo.setStringPermissions(p.getPermissionValue());
				simpleAuthorizationInfo.setStringPermissions(permissons);
				//simpleAuthorizationInfo.addStringPermission(p.getPermissionValue());
			}
		}
		return simpleAuthorizationInfo;
	}

	/**
	 * 认证
	 */
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken arg0) throws AuthenticationException {
		System.out.println("认证");
		//获取当前操作主体用户名
		String userName = (String) arg0.getPrincipal();
		User user=userService.findByUname(userName);
		//判断用户是否存在
		if(user==null) {
			return null;
		}else {//判断密码是否正确
			/**
			 * 1、操作主体，或主体用户名
			 * 2、主体密码
			 * 3、当前的realm对象
			 */
			SimpleAuthenticationInfo simpleAuthenticationInfo=new SimpleAuthenticationInfo(user,user.getUserPassWord(),getName());
			System.out.println(MD5.JiaM(user.getUserPassWord()));
			
			return simpleAuthenticationInfo;
		}
		
	}
 
}
